package com.gitee.wsl.jvm.ext.base

import com.gitee.wsl.ext.reflect.ReflectionExt
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy
import java.util.concurrent.atomic.AtomicReference


/**
 * Returns a proxy instance that implements `interfaceType` by dispatching method
 * invocations to `handler`. The class loader of `interfaceType` will be used to
 * define the proxy class. To implement multiple interfaces or specify a class loader, use [ ][Proxy.newProxyInstance].
 *
 * @throws IllegalArgumentException if `interfaceType` does not specify the type of a Java
 * interface
 */
fun <T> ReflectionExt.newProxy(interfaceType: Class<T>, handler: InvocationHandler): T? {
    //checkNotNull(handler)
    //checkArgument(interfaceType.isInterface, "%s is not an interface", interfaceType)
    val `object`: Any = Proxy.newProxyInstance(
        interfaceType.classLoader, arrayOf<Class<*>>(interfaceType), handler
    )
    return interfaceType.cast(`object`)
}

@Suppress("UnstableApiUsage")
fun <T> Class<T>.newProxy(handler: InvocationHandler): T? = ReflectionExt.newProxy(this, handler)

/**
 * @Description:
 * @Author: JIULANG
 * @Data: 2022/10/27 12:19
 */

class AtomicRef<T>  constructor(initialValue: T) {
    private val atomic = AtomicReference(initialValue)

    var value: T
        get() = atomic.get()
        set(value) = atomic.set(value)

    fun compareAndSet(expect: T, update: T): Boolean = atomic.compareAndSet(expect, update)
}